package cn.cocho.android.mc.comp.webview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import cn.cocho.android.mc.R;

/**
 * Created by Joyce on 15/3/9.
 */
public class McWebView extends WebView {
    Context context;
    private View loadingView;
    private String currentUrl;
    /**
     * js调用java中的方法时使用的对象名
     */
    public static final String jsObjectName = "mobile_android";

    public McWebView(Context context) {
        super(context);
    }

    public McWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public McWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init(attrs);
        initWebView();
    }

    private void init(AttributeSet attrs) {
        TypedArray tdarr = context.obtainStyledAttributes(attrs, R.styleable.McWebView);
        int resId = tdarr.getResourceId(R.styleable.McWebView_loading_view, 0);
        if(resId != 0){
            LayoutInflater inflater = LayoutInflater.from(context);
            try {
                loadingView = inflater.inflate(resId, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        tdarr.recycle();
    }


    private void initWebView() {
        //设置支持Javascript
        getSettings().setJavaScriptEnabled(true);
//        getSettings().setPluginsEnabled(true);
        //解决加载html页面时右侧会出现小片空白
        setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        // 自适应屏幕
        getSettings().setUseWideViewPort(true);
        getSettings().setLoadWithOverviewMode(true);
        // 支持缩放
        getSettings().setSupportZoom(true);
        getSettings().setBuiltInZoomControls(true);

        //webview链接点击后仍然进入webview中
        setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                currentUrl = url;
                return false;
            }
        });
        //点击返回能回到上一页
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && canGoBack()) {  //表示按返回键时的操作
                        goBack();
                        return true;
                    }
                }
                return false;
            }
        });

        initLoadingView();
    }

    /**
     * 设置是否使用缓存
     *
     * @param isEnabled
     */
    public void setCacheEnabled(boolean isEnabled) {
        if (isEnabled) {
            getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //设置缓存模式：优先使用缓存
            // 开启 DOM storage API 功能
            getSettings().setDomStorageEnabled(true);
            //开启 database storage API 功能
            getSettings().setDatabaseEnabled(true);
            //开启 Application Caches 功能
            getSettings().setAppCacheEnabled(true);
        } else {
            clearCache();
            getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置缓存模式：不使用缓存
        }
    }

    /**
     * 清除缓存
     */
    public void clearCache() {
        context.deleteDatabase("webview.db");
        context.deleteDatabase("webviewCache.db");
    }

    public String getCurrentUrl (){
        if (null == currentUrl){
            currentUrl = getUrl();
        }
        return currentUrl;
    }

    /**
     * 初始化loadingView的布局及显示
     * loadingView：在网页跳转时显示的自定义加载界面，避免出现空白
     */
    private void initLoadingView() {
        if (null != getLoadingView()) {
            FrameLayout container = new FrameLayout(context);
            this.addView(container, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            container.addView(loadingView);

            setWebViewClient(new WebViewClient() {

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    loadingView.setVisibility(View.GONE);
                }

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    loadingView.setVisibility(View.VISIBLE);
                }

            });

//            setWebChromeClient(new WebChromeClient(){
//                @Override
//                public void onProgressChanged(WebView view, int newProgress) {
//
//                    if (newProgress>0&&newProgress<50){
//                        loadingView.setVisibility(View.VISIBLE);
//                    }else {
//                        loadingView.setVisibility(View.GONE);
//                    }
//
//                }
//            });
        }
    }

    /**
     * 指定loadingView的布局view
     * loadingView：在网页跳转时显示的自定义加载界面，避免出现空白
     */
    public void setLoadingView(View loadingView) {
        this.loadingView = loadingView;
        initLoadingView();
    }

    public View getLoadingView() {
        return loadingView;
    }
}